<template>
	<view class="almost-lottery">
		<view class="top-info">
			天天抽奖 好运不断
		</view>
		<view class="almost-lottery__wheel">
			<almost-lottery :lottery-size="lotteryConfig.lotterySize" :action-size="lotteryConfig.actionSize"
				:ring-count="15" :duration="3" :prize-list="prizeList" :prize-index="prizeIndex"
				@reset-index="prizeIndex = -1" @draw-start="handleDrawStart" @draw-end="handleDrawEnd"
				@finish="handleDrawFinish" v-if="prizeList.length" />
			<view class="almost-lottery__count">
				<text class="text">剩余可抽奖 {{ freeNum }} 次</text>
			</view>
		</view>
		<!-- rule -->
		<view class="almost-lottery__rule">
			<view class="rule-head">
				<view class="line"></view>
				<text class="title">活动规则</text>
				<view class="line"></view>
			</view>
			<view class="rule-body">
				<view class="item">
					<view class="number">1</view>
					<view class="text">
						<text>抽奖细则：</text>
						<text>签到一次，可以抽奖一次哦！</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import AlmostLottery from '@/uni_modules/almost-lottery/components/almost-lottery/almost-lottery.vue'
	import {
		clearCacheFile
	} from '@/uni_modules/almost-lottery/utils/almost-utils.js'
	export default {
		name: 'Home',
		components: {
			AlmostLottery
		},
		data() {
			return {
				// 开启调试模式
				isDev: true,

				// 以下是转盘配置相关数据
				lotteryConfig: {
					// 抽奖转盘的整体尺寸，单位rpx
					lotterySize: 600,
					// 抽奖按钮的尺寸，单位rpx
					actionSize: 200
				},

				// 以下是转盘 UI 配置
				// 转盘外环图，如有需要，请参考替换为自己的设计稿
				lotteryBg: '/static/lottery-bg.png',
				// 抽奖按钮图
				actionBg: '/static/action-bg.png',

				// 以下是奖品配置数据
				// 奖品数据
				prizeList: [],
				// 奖品是否设有库存
				onStock: true,
				// 中奖下标
				prizeIndex: -1,

				// 是否正在抽奖中，避免重复触发
				prizeing: false,

				// 以下为中奖概率有关数据
				// 是否由前端控制概率，默认不开启，强烈建议由后端控制
				onFrontend: false,
				// 权重随机数的最大值
				prizeWeightMax: 0,
				// 权重数组
				prizeWeightArr: [],

				// 以下为业务需求有关示例数据
				// 当日免费抽奖次数余额
				freeNum: 0,
				isAuth:0
			}
		},
		onShow() {
			this.queryAuthResult();
		},
		methods: {
			// 重新生成
			handleInitCanvas() {
				clearCacheFile()
				this.prizeList = []
				this.getPrizeList()
			},
			// 获取奖品列表
			async getPrizeList() {
				let that = this;
				uni.showLoading({
					title: '奖品准备中...'
				})
				// 等待接口返回的数据进一步处理
				let res = await this.requestApiGetPrizeList();
				console.log(res)
				let goods = res.data.lotteryGoodsVos;
				if (goods != undefined && goods.length > 0) {
					this.prizeList = goods; //商品列表
					this.freeNum = res.data.lotteryCount; //抽奖次数
					this.isAuth = res.data.isYunGouAuth;//认证isYunGouAuth
				} else {
					uni.hideLoading()
					uni.showToast({
						title: '获取奖品失败',
						mask: true,
						icon: 'none'
					})
				}
			},
			requestApiGetPrizeList() {
				let that = this;
				return new Promise(function(resolve, reject) {
					uni.request({
						header:{
							'sessionKey': uni.getStorageSync('sessionKey'),
							'X-Requested-With': 'XMLHttpRequest',
							"Accept": "application/json",
							"Content-Type": "application/json; charset=UTF-8"
						},
						url: that.baseUrl+'lottery/getLotteryInfo',
						method: 'POST',
						success: (res) => {
							console.log(res.data)
							resolve(res.data)
						}
					})
				})
			},
			toYungouAuth(){//yungou授权
					let that = this;
					uni.request({
						url: that.baseUrl+'wxAuth/getAuthUrl',
						header:{
							'sessionKey': uni.getStorageSync('sessionKey'),
							'X-Requested-With': 'XMLHttpRequest',
							"Accept": "application/json",
							"Content-Type": "application/json; charset=UTF-8"
						},
						method: 'GET',
						success: (res) => {
							uni.setStorageSync('webAuthSrc', res.data.data);
							uni.navigateTo({
								url:'webAuth'
							})
						}
						
					})
			},
			queryAuthResult(){
				let that = this;
				uni.request({
					header:{
						'sessionKey': uni.getStorageSync('sessionKey'),
						'X-Requested-With': 'XMLHttpRequest',
						"Accept": "application/json",
						"Content-Type": "application/json; charset=UTF-8"
					},
					url: that.baseUrl+'wxAuth/queryAuthResult',
					method: 'GET',
					success: (res) => {
						that.isAuth = res.data.data;
					}
					
				})
			},
			requestApiGetStartLottery() {
				let that = this;
				return new Promise(function(resolve, reject) {
					uni.request({
						header:{
							'sessionKey': uni.getStorageSync('sessionKey'),
							'X-Requested-With': 'XMLHttpRequest',
							"Accept": "application/json",
							"Content-Type": "application/json; charset=UTF-8"
						},
						url: that.baseUrl+'lottery/toStartLottery', //仅为示例，并非真实接口地址。
						method: 'POST',
						success: (res) => {
							if(res.data.code == 507){
								uni.showModal({
								    title: '提示',
									cancelText:'稍后抽奖',
									confirmText:'去授权',
								    content: '为了保证抽奖现金到您的微信余额,请先授权',
								    success: function (res) {
								        if (res.confirm) {
								           that.toYungouAuth();
								        }else{
											uni.showToast({
												title: '您已取消抽奖',
												mask: true,
												icon: 'none'
											})
										}
								    }
								});
								return;
							}
							if(res.data.code != 200){
								uni.showToast({
									title: res.data.msg,
									mask: true,
									icon: 'none'
								})
								return;
							}
							
							resolve(res.data)
						},
						complete() {
							that.prizeing = false;
						}
					})
				})
			},
			// 本次抽奖开始
			handleDrawStart() {
				console.log('触发抽奖按钮')
				let that = this;
				console.log("isAuth:"+this.isAuth ==0);
				if(this.isAuth === 0){
					uni.showModal({
					    title: '提示',
						cancelText:'稍后抽奖',
						confirmText:'去授权',
					    content: '为了保证抽奖现金到您的微信余额,请先授权',
					    success: function (res) {
					        if (res.confirm) {
					           that.toYungouAuth();
					        }else{
								uni.showToast({
									title: '您已取消抽奖',
									mask: true,
									icon: 'none'
								})
							}
					    }
					});
					return;
				}
				
				if (this.prizeing) return;
				this.prizeing = true
				this.remoteGetPrizeIndex();
			},
			async remoteGetPrizeIndex() {
				let res = await this.requestApiGetStartLottery()
				for (let i = 0; i < this.prizeList.length; i++) {
					let item = this.prizeList[i]
					if (item.prizeId === res.data) {
						// 中奖下标
						this.prizeIndex = i
						break
					}
				}
			},
			// 本次抽奖结束
			handleDrawEnd() {
				console.log('旋转结束，执行拿到结果后到逻辑')
				// 旋转结束后，开始处理拿到结果后的逻辑
				this.prizeing = false;
				let prizeName = this.prizeList[this.prizeIndex].prizeName;
				let tipContent = '';
				if (prizeName === '谢谢参与') {
					tipContent = '很遗憾，没有中奖，请再接再厉！';
				} else {
					this.freeNum--;
					tipContent = `恭喜您，获得 ${prizeName} ！稍后到您的微信余额`;
				}
				uni.showModal({
					content: tipContent,
					showCancel: false
				})
			},
			// 抽奖转盘绘制完成
			handleDrawFinish(res) {
				console.log('抽奖转盘绘制完成', res)

				let stoTimer = setTimeout(() => {
					clearTimeout(stoTimer)
					stoTimer = null

					uni.showToast({
						title: res.msg,
						mask: true,
						icon: 'none'
					})
				}, 50)
			}
		},
		onLoad() {
			this.handleInitCanvas()
		},
		onUnload() {
			uni.hideLoading()
		}
	}
</script>

<style lang="scss" scoped>
	.almost-lottery {
		flex: 1;
		background-color: #FF893F;
		height: 100vh;
		padding-top: 180rpx;
	}

	.top-info {
		margin-bottom: 50rpx;
		text-align: center;
		color: #fff;
		font-size: 46rpx;
		font-weight: 900;
	}


	.almost-lottery__wheel {
		text-align: center;

		.almost-lottery__count {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			text-align: center;
			padding: 40rpx 0;
			font-size: 36rpx;
			font-weight: 800;
		}

		.text {
			color: #FFFFFF;
			font-size: 24rpx;
		}
	}

	.almost-lottery__rule {
		padding: 0 28rpx;
		color: #FFF8CB;

		.rule-head {
			display: flex;
			justify-content: space-around;
			align-items: center;
			margin: 40rpx 0;

			.line {
				flex: 1;
				height: 1px;
				background-color: #FFF3A5;
			}

			.title {
				width: 280rpx;
				color: #F63857;
				line-height: 70rpx;
				text-align: center;
				margin: 0 20rpx;
				border-radius: 8rpx;
				background-image: linear-gradient(0deg, rgba(255, 242, 158, 1), rgba(255, 244, 168, 1));
			}
		}

		.rule-body {
			color: #FFF8CB;
			font-size: 24rpx;
			padding: 10rpx 0 40rpx;

			.item {
				display: flex;
				margin-bottom: 10rpx;
			}

			.number {
				position: relative;
				top: 4rpx;
				width: 28rpx;
				height: 28rpx;
				line-height: 28rpx;
				text-align: center;
				color: #F63857;
				background: #FFF8CB;
				border-radius: 50%;
				margin-right: 10rpx;
			}

			.text {
				flex: 1;
			}

			.item-rule .text {
				display: flex;
				flex-direction: column;
			}
		}
	}

	.almost-lottery__action-dev {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		width: 400rpx;
		height: 80rpx;
		border-radius: 10rpx;
		text-align: center;
		background-color: red;
		margin: 0 auto 40rpx;

		.text {
			color: #FFFFFF;
			font-size: 28rpx;
		}
	}
</style>
